package znet

import (
	"errors"
	"fmt"
	"sync"
	"zinx/ziface"
)

type ConnManager struct {
	//连接信息集合
	connections map[uint32]ziface.IConnection
	//保护连接集合的读写锁
	connLock sync.RWMutex
}

func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]ziface.IConnection),
	}
}

func (cm *ConnManager) Add(conn ziface.IConnection) {
	//添加需要加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()
	cm.connections[conn.GetConnID()] = conn
	fmt.Println("connID[", conn.GetConnID(), "]", " add to ConnManager successfully: conn num = ", cm.Len())
}

func (cm *ConnManager) Remove(conn ziface.IConnection) {
	//删除需要加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()
	delete(cm.connections, conn.GetConnID())
	fmt.Println("connID[", conn.GetConnID(), "]", " remove from ConnManager successfully: conn num = ", cm.Len())
}

func (cm *ConnManager) Get(connId uint32) (ziface.IConnection, error) {
	//获取需要加读锁
	cm.connLock.RLock()
	defer cm.connLock.RUnlock()
	if conn, ok := cm.connections[connId]; ok {
		return conn, nil
	}
	return nil, errors.New("conn not found")
}

func (cm *ConnManager) Len() int {
	return len(cm.connections)
}

func (cm *ConnManager) ClearConn() {
	//删除需要加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()
	for connId, conn := range cm.connections {
		//停止连接
		conn.Stop()
		//从集合中删除连接
		delete(cm.connections, connId)
	}
	fmt.Println("Clear All conn successfully! conn num = ", cm.Len())
}
